import { CustomElementStyleId, logger } from '../types/constants'
import { SYMBOLS } from '../types/interfaces'

export class StyleOrder {
  private name: string = 'StyleOrder'
  private static instance: StyleOrder
  private readonly themeStyleId: string = CustomElementStyleId.ThemeCss
  private readonly customStyleId: string = CustomElementStyleId.CustomCss
  private observer: MutationObserver | null = null

  /**
   * 获取单例实例
   */
  public static getInstance(): StyleOrder {
    if (!StyleOrder.instance) {
      StyleOrder.instance = new StyleOrder()
    }
    return StyleOrder.instance
  }

  /**
   * 启动监控
   */
  public startMonitoring(): void {
    // 先立即检查一次
    this.checkAndFixOrder()

    // 设置 MutationObserver 持续监控
    this.observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        const addedStyles = [...mutation.addedNodes].filter(
          (node): node is HTMLElement =>
            node.nodeName === 'STYLE'
            && !!(node as HTMLElement).id // 类型断言
            && !!([this.themeStyleId, this.customStyleId].includes((node as HTMLElement).id)),
        )
        if (addedStyles.length > 0) {
          this.checkAndFixOrder()
        }
      })
    })

    this.observer.observe(document.head, {
      childList: true,
      subtree: false,
    })
  }

  /**
   * 停止监控
   */
  public stopMonitoring(): void {
    this.observer?.disconnect()
    this.observer = null
  }

  /**
   * 检查并修正顺序
   */
  private checkAndFixOrder(): void {
    const themeStyle = document.getElementById(this.themeStyleId)
    const customStyle = document.getElementById(this.customStyleId)

    // 如果任一元素不存在，则跳过
    if (!themeStyle || !customStyle) {
      return
    }

    // 检查顺序是否正确（themeStyle 应该在 customStyle 之前）
    const isOrderCorrect = themeStyle.compareDocumentPosition(customStyle)
      & Node.DOCUMENT_POSITION_FOLLOWING

    if (!isOrderCorrect) {
      logger.warn(`[${this.name}] 检测到样式顺序错误，正在修正...`)
      this.forceCorrectOrder(themeStyle, customStyle)
    }
  }

  /**
   * 强制修正顺序
   */
  private forceCorrectOrder(themeStyle: HTMLElement, customStyle: HTMLElement): void {
    // 先移除 customStyle
    customStyle.remove()

    // 在 themeStyle 后插入 customStyle
    themeStyle.after(customStyle)

    logger.warn(`[${this.name}] ${SYMBOLS.STATUS.SUCCESS} 已修正样式顺序：${this.themeStyleId} -> ${this.customStyleId}`)
  }
}
